<?php

namespace XWAM\Model;

/**
 * ShoppingCart 模型类
 *
 * @since VER:1.0; DATE:2016-9-3; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class ShoppingCartModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 't_porg_shoppingcart';    

    function addCart($product_id, $number, $user_name) {
        $data = array(
            'product_id' => $product_id,
            'user_name' => $user_name,
        );
        if ($this->where($data)->count() > 0) {
            // 购物车已经存在则只增加数量
            $return = $this->where($data)->setInc('number', $number);
            return $this->returnMsg($result);
        }
        $data['number'] = $number;
        $result = $this->add($data);
        return $this->returnMsg($result);
    }

    function getCount($user_name) {
        return $this->where(array('user_name' => $user_name))->count();
    }

    function getPagingList(&$page, $where) {
        $options = array(
            'table' => 't_porg_shoppingcart c left join t_porg_product_goods g on c.product_id=g.id',
            'where' => $where,
            'field' => 'c.id, c.product_id, c.number, c.user_name, g.title, g.market_price, g.price, g.picture_url, (g.price * c.number) as subtotal',
        );
        return $this->selectPaging($page, $options);
    }

    function changeNumber($id = 0, $number = 0) {
        $subtotal = 0;
        if ($id && $number) {
            $this->where(array('id' => $id))->setField('number', $number);
            // 计算小计金额
            $product_id = $this->where(array('id' => $id))->getField('product_id');
            $price = $this->table('t_porg_product_goods')->where(array('id' => $product_id))->getField('price');
            $subtotal = $price * $number;
        }
        echo $subtotal;
    }

    function get_cart_summary($ids = '', $user_name = '') {
        $where = $ids ? "c.id in ($ids)" : "c.user_name='$user_name'";
        $list = $this->query('select c.number * g.price as amount, c.number * g.market_price as market_amount from t_porg_shoppingcart c inner join t_porg_product_goods g on c.product_id=g.id where ' . $where);
        if ($list) {
            $aout = $list[0];
            $aout['save_amount'] = $aout['market_amount'] - $aout['amount'];
            $aout['save_rate'] =ceil($aout['save_amount'] / $aout['market_amount'] * 100);
        } else {
            $aout = array(
                'amount' => 0,
                'market_amount' => 0,
                'save_amount' => 0,
                'save_rate' => 0,
            );
        }
        return $aout;
    }

}
